<?php
require_once("VenueMusic.php");
require_once("Lastfm.php");
require_once("RSS.php");
require_once("LineupItem.php");
require_once("Artist.php");

/**
 * Handles the venue-lineup.
 *
 * @author Magnus Stoveland <mstoveland@gmail.com>
 *
 */
class Venue
{
    /**
     * Returns array with fetched row
     * 
     * @param int $venueId
     * @return array fetched row
     */
    function getVenue($venueId) {
        $query = "SELECT * FROM venues WHERE id = ".$venueId." AND active = 1 ORDER BY name";
        $db = Database::getInstance();
        $result = $db->query($query);
        return mysql_fetch_array($result);
    }

    /**
     * Parses $url for mateches to $regex pattern
     *
     * @param string $url
     * @param string $regex pattern
     * @return array of Artist-objects
     */
    function parse($venue_id) {
        // Fetch from DB
        $query = "SELECT * FROM venues WHERE id=".$venue_id." AND active=1";
        $db = Database::getInstance();
        $result = $db->query($query);
        $venue = mysql_fetch_assoc($result);
        if($venue['request_type'] == "rss") {
            return Venue::parseRSS($venue['url']);
        }
        $file = Venue::readFile($venue['url'], $venue['request_type']);
        if(preg_match_all("/".$venue['regex']."/siU", $file, $matches)) {
            if(count($matches) < 3) {
                Venue::_raiseParseLock($venue_id, $venue['url'], "parselock #1");
            }
            foreach($matches[0] as $key => $match) {
                $artist = new Artist($matches[2][$key]);
                /* TO BE CONSIDERED 
                if(empty($venueMusic->artist) && !isset($ok)) {
                    Venue::_raiseParseLock($venue_id, $venue['url'], "parselock #3");
                    $ok = "ok";
                }
                */
                // Strip nationality parenthesis [is there a better solution?]
                if(strstr($artist->name, " (")) {
                    $temp = explode(" (", $artist->name);
                    $artist->name = $temp[0];
                }
                $artist->url = $matches[1][$key];
                // Adds host if relative url [Could this be tuned?]
                if(!strstr($artist->url, "http://")) {
                    preg_match('@^(?:http://)?([^/]+)@i', $url, $match);
                    $host = "http://".$match[1];
                    $artist->url = $host.$artist->url;
                }
                
                // !! Make use of artist.search web service to verify/falsify artist existence
                $lineupItem = new LineupItem();
                $lineupItem->title = $artist->name;
                $lineupItem->artist = $artist;
                $artistList[] = $lineupItem;
            }
        } else {
            Venue::_raiseParseLock($venue_id, $venue['url'], "parselock #2");
        }
        return $artistList;
    }
    
    /*
     * Reads url and return the content as string
     * 
     * @param string $url
     * @param string $method ["curl", ""] (opotional)
     * @return string $contents
     */
    function readFile($url, $method = "") {
        if ($method == "curl") {
            // Create a new cURL resource
            $ch = curl_init();
            // Set URL and other appropriate options
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            $contents = curl_exec($ch);
            if(!$contents) {
                trigger_error("Unable to open url: <strong>".$url."</strong>", E_USER_ERROR);
            }
            curl_close($ch);
        } else {
            ini_set('allow_url_fopen', 'on');
            $fp = @fopen($url, "r");
            if ($fp) {
                $contents = file_get_contents($url);
            } else {
                trigger_error("Unable to open url: <strong>".$url."</strong>", E_USER_ERROR);
            }
            fclose($fp);
        }
        return $contents;
    }

    function parseRSS($url) {
		$rss =& new XML_RSS($url);
		$rss->parse();
    
		foreach($rss->getItems() as $item) {
		    $artist = new Artist();
		    // TEMPORARY FOR SAMFUNDET ONLY
            $temp = explode(" - ", $item['title']); 
		    $artist->name = $temp[0];
		    $artist->url = $item['link'];
		    //$artist->avatar = Lastfm::saveArtistAvatar($artist->name);
		    $music_list[] = $artist;
		}
		return $music_list;
    }
    
    /**
     * This functions removes the actual venue from the Musiceye venue list and notifies admin about the situation.
     * 
     * @param int $venue_id
     * @param url $venue_url
     * @param string $info
     */
    function _raiseParseLock($venue_id, $venue_url, $info) {
        // Temporarily hide the venue until regex is fixed
        $query = "UPDATE venues SET active=0 WHERE id=".$venue_id;
        $db = Database::getInstance();
        $result = $db->query($query);
         
        // Notify admins
        Mail::sendNotification("praseLock", "Venue: ".$venue_id."\n\n".$venue_url."\n\n".$info);
    }
    

}
?>